<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../../css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="../../css/header.css" />

	</head>

	<body>

		<header class="mui-bar mui-bar-nav title">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left" style="color: white;"></a>
			<button type="button" class="mui-btn mui-btn-outlined mui-pull-right" id="btn_nickname" style="color: white;">保存</button>
			<h1 class="mui-title title-color" style="text-align: left; margin-top: 2px;">更改名字</h1>
		</header>

		<div class="mui-content">
			<div class="mui-input-row" style="margin-top: 15px;">
				<input id="nickname" type="text" class="mui-input-speech mui-input-clear" placeholder="修改昵称">
				<p style="padding: 0 15px;">好名字可以让你的朋友更容易记住你</p>
			</div>
		</div>

		<script src="../../js/mui.min.js"></script>
		<script src="../../js/app.js"></script>
		<script type="text/javascript">
			mui.init()

			mui.plusReady(function() {
				var user = app.getCacheUser();
				var oldNickname = user.nickname;
				var nickname = document.getElementById("nickname");
				nickname.value = oldNickname;

				// 提交事件，修改昵称
				var btn_nickname = document.getElementById("btn_nickname");
				btn_nickname.addEventListener("tap", function() {
					var newNickname = nickname.value;

					if (newNickname == oldNickname) {
						app.showToast("昵称未改变", "error");
						return false;
					}
					if (newNickname.length < 1) {
						app.showToast("昵称长度太短", "error");
						return false;
					}
					if (newNickname.length > 8) {
						app.showToast("昵称不能超过8位", "error");
						return false;
					}
					var params = {
						account: user.account,
						nickname: newNickname
					};
					plus.nativeUI.showWaiting("请稍微...");
					mui.ajax(app.serverUrl + "/user/nickname", {
						data: params,
						dataType: 'json', //服务器返回json格式数据
						type: 'put', //HTTP请求类型
						timeout: 10000, //超时时间设置为10秒；
						headers: {
							'Content-Type': 'application/json',
							'auth-token': app.getAuthToken()
						},
						success: function(res) {
							//服务器返回响应，根据响应结果，分析是否登录成功；
							plus.nativeUI.closeWaiting();

							if (res.code == 0) {
								// 登录或者注册成功之后，保存全局用户对象到本地缓存
								user.nickname = newNickname;
								app.setCacheUser(user);
								// 触发另外一个webview的自定义事件，可以使用 mui.fire()
								var meWebview = plus.webview.getWebviewById("me.html");
								mui.fire(meWebview, "refresh");

								// 页面跳转
								mui.back();
							} else {
								app.showToast(res.msg, "error");
							}
						}
					});
				});

			});
		</script>

	</body>

</html>
